<template>
  <div>
    <el-upload
      action="#"
      :http-request="onRequest"
      list-type="picture-card"
      :on-preview="handlePictureCardPreview"
      :on-remove="handleRemove"
      :file-list="fileList"
      :on-change="onChange"
      :before-upload="beforeUpload"
    >
      <i class="el-icon-plus" />
    </el-upload>

    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>

  </div>
</template>

<script>
import { upLoadIMG } from '@/api/parameter'
export default {
  name: 'UploadImage',
  data() {
    return {
      dialogImageUrl: '',
      dialogVisible: false,
      fileList: []
    }
  },
  methods: {
    async onRequest({ file }) {
      const fd = new FormData()
      fd.append('file', file)
      const res = await upLoadIMG(fd)
      this.fileList[this.fileList.length - 1].url = res.url
      this.fileList[this.fileList.length - 1].tmp_path = res.tmp_path
      this.$emit('on-success', this.fileList)
      // this.fileList[this.fileList.length - 1] = { ...this.fileList[this.fileList.length - 1], ...res }
    },
    onChange(file, fileList) {
      this.fileList = fileList
    },
    handleRemove(file, fileList) {
      this.fileList = fileList
      this.$emit('on-success', this.fileList)
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    beforeUpload(file) {
      const maxSize = 2 * 1024 * 1024
      const fileType = ['image/gif', 'image/jpeg', 'image/png']
      if (!fileType.includes(file.type)) {
        this.$message.error('请上传正确格式的图片')
        return false
      }
      if (file.size > maxSize) {
        this.$message.error('请选择2Mb大小以内的图片')
        return false
      }
    }
  }
}
</script>
